import React, {PureComponent} from 'react';
import {Row, Col, Form, Button, Divider, Table, Alert, Spin} from 'antd';
import {PAGE, TABLE, PAGINATION_OPTIONS, COMMON_TABLE_QUERY_FAIL_TEXT,
    COMMON_TABLE_EMPTY_TEXT, FORM_OPTIONS, DATE_FORMAT, ROWSELECTION_FIXED_COLUMN_WIDTH} from '../../constants';
import TextInput from 'Shared/components/TextInput';
import WrappedTag from '../../common/WrappedTag';
import {getWarrantyPolicyItem, getWarrantyPolicyItemDetail} from '../api';
import {warrantyPolicyType, warrantyPolicyStatus} from '../../Enum';
import {conventEnumValueToString, conventSorter, formatDateTime, uuid} from '../../utils';
const FormItem = Form.Item;
import styles from '../style.css';
import {formatMessage} from '../intl';
import {formatNumber} from '../../common/localize';
class DetailSelectPanel extends PureComponent {
    state = {
        keys: [],
        rows: [],
        code: '',
        name: '',
        isFetching: false,
        loading: false,
        tips: '',
        data: {},
        message: '',
        pageIndex: PAGE.index,
        pageSize: PAGE.smallSize,
        sortField: 'code',
        isDesc: false,
        currentCondition: {}
    };
    handleTableChange = (pagination, filters, sorter) => {
        const oldCondition = this.state.currentCondition;

        if(pagination.current - 1 === oldCondition.pageIndex && pagination.pageSize === oldCondition.pageSize) {
            const sortOptions = conventSorter(sorter);
            const condition = Object.assign({}, oldCondition, sortOptions, {
                pageIndex: PAGE.index
            });
            this.onQuery(condition);
            this.setState({
                sortField: sortOptions.sortField,
                isDesc: sortOptions.isDesc
            });
        }
    };
    handleFilterPressEnter = (value, name) => {
        this.setState({
            [name]: value
        }, this.onClickSearchBtn);
    };
    onQuery = condition => {
        this.setState({
            isFetching: true
        });
        condition.status = warrantyPolicyStatus.生效;
        getWarrantyPolicyItem(condition).then(res => {
            if(res.ok)
                this.setState({
                    isFetching: false,
                    message: '',
                    data: res.data,
                    currentCondition: condition
                });
            else
                this.setState({
                    isFetching: false,
                    data: [],
                    message: res.message
                });
        });
    };
    onClickSearchBtn = () => {
        const condition = {
            code: this.state.code,
            name: this.state.name,
            pageIndex: PAGE.index,
            pageSize: this.state.pageSize,
            sortField: this.state.sortField,
            isDesc: this.state.isDesc
        };
        this.onQuery(condition);
    };
    onPageIndexChange = current => {
        const condition = {...this.state.currentCondition};
        condition.pageIndex = current - 1;
        this.onQuery(condition);
    };
    onPageSizeChange = (current, pageSize) => {
        const condition = {...this.state.currentCondition};
        condition.pageIndex = PAGE.index;
        condition.pageSize = pageSize;
        this.onQuery(condition);
        this.setState({
            pageSize
        });
    };
    onChange = (value, name) => {
        this.setState({
            [name]: value
        });
    };

    onChangeRadio = (keys, rows) => {
        this.setState({
            keys,
            rows
        });
    }
    onCloseTag = () => {
        this.setState({
            keys: [],
            rows: []
        });
    }
    onSubmit = data => {
        this.setState({
            loading: true,
            tips: formatMessage({
                id: 'detailSelectPanel.submitTips',
                defaultMessage: '正在查询条款详情'
            })
        });
        getWarrantyPolicyItemDetail(data.id).then(res => {
            if(res.ok) {
                const detail = res.data;
                detail.id = uuid();
                this.props.onSelect(detail);
            } else
                this.setState({
                    loading: false,
                    tips: ''
                });
        });
    }
    onDoubleClick = record => {
        this.onSubmit(record);
    }
    onConfirm = () => {
        this.onSubmit(this.state.rows[0]);
    }
    render() {
        const {code, name, isFetching, data, message} = this.state;
        const {pageIndex, pageSize} = this.state.currentCondition;
        const columns = [
            {
                title: formatMessage({
                    id: 'detailSelectPanel.code',
                    defaultMessage: '编号'
                }),
                dataIndex: 'code',
                sorter: true,
            },
            {
                title: formatMessage({
                    id: 'detailSelectPanel.name',
                    defaultMessage: '名称'
                }),
                dataIndex: 'name',
                sorter: true,
            },
            {
                title: formatMessage({
                    id: 'detailSelectPanel.warrantyPolicyType',
                    defaultMessage: '整车索赔政策类型'
                }),
                dataIndex: 'warrantyPolicyType',
                sorter: true,
                render: text => conventEnumValueToString(warrantyPolicyType, text)
            },
            {
                title: formatMessage({
                    id: 'detailSelectPanel.warrantyMileage',
                    defaultMessage: '索赔里程'
                }),
                dataIndex: 'warrantyMileage',
                render: text => formatNumber(text)
            },
            {
                title: formatMessage({
                    id: 'detailSelectPanel.warrantyMonth',
                    defaultMessage: '索赔月份'
                }),
                dataIndex: 'warrantyMonth',
                render: text => formatNumber(text)
            },
            {
                title: formatMessage({
                    id: 'detailSelectPanel.saleStartDate',
                    defaultMessage: '发车开始时间'
                }),
                dataIndex: 'saleStartDate',
                render: text => formatDateTime(text, DATE_FORMAT),
            },
            {
                title: formatMessage({
                    id: 'detailSelectPanel.saleEndDate',
                    defaultMessage: '发车结束时间'
                }),
                dataIndex: 'saleEndDate',
                render: text => formatDateTime(text, DATE_FORMAT),
            },
        ];
            
        const pagination = {
            total: data.totalElements,
            current: pageIndex + 1,
            pageSize,
            onShowSizeChange: this.onPageSizeChange,
            onChange: this.onPageIndexChange,
            ...PAGINATION_OPTIONS
        };

        const onRow = record => ({
            onDoubleClick: () => this.onDoubleClick(record)
        });
        const rowSelection = {
            type: 'radio',
            fixed: true,
            columnWidth: ROWSELECTION_FIXED_COLUMN_WIDTH,
            onChange: this.onChangeRadio,
            selectedRowKeys: this.state.keys,
        };
        const selectTag = (<span>{formatMessage({
            id: 'detailSelectPanel.selectTag',
            defaultMessage: '，已选择'
        })} {this.state.rows.map(tag =>
            <WrappedTag key={tag.id} id={tag.id} closable onClose={this.onCloseTag}>
                {tag.name}
            </WrappedTag>)}</span>);
        const alertMessage = (
            <Row>
                <Col span={18}><span>{formatMessage({
                    id: 'detailSelectPanel.alertMessage',
                    defaultMessage: '可以双击行选择'
                })}</span>{this.state.rows.length ? selectTag : ''}</Col>
                <Col span={6} className="col-align-right">
                    <Button type="primary" size="small" onClick={this.onConfirm}>{formatMessage({
                        id: 'detailSelectPanel.btn.confirm',
                        defaultMessage: '确认'
                    })}</Button>
                </Col>
            </Row>);

        return (
            <Spin spinning={this.state.loading} tip={this.state.tips}>
                <Row className="form-standard operation-buttons">
                    <Col {...FORM_OPTIONS.col}>
                        <FormItem
                            label={formatMessage({
                                id: 'detailSelectPanel.code',
                                defaultMessage: '编号'
                            })}
                            {...FORM_OPTIONS.item}>
                            <TextInput name="code" value={code}
                                onPressEnter={this.handleFilterPressEnter} onBlur={this.onChange} />
                        </FormItem>
                    </Col>
                    <Col {...FORM_OPTIONS.col}>
                        <FormItem
                            label={formatMessage({
                                id: 'detailSelectPanel.name',
                                defaultMessage: '名称'
                            })}
                            {...FORM_OPTIONS.item}>
                            <TextInput name="name" value={name}
                                onPressEnter={this.handleFilterPressEnter} onBlur={this.onChange} />
                        </FormItem>
                    </Col>
                    <Col
                        className={styles.selectPanelBtn} span={8}>
                        <Button type="primary" onClick={this.onClickSearchBtn}>
                            {formatMessage({
                                id: 'detailSelectPanel.btn.query',
                                defaultMessage: '查询'
                            })}
                        </Button>
                    </Col>
                </Row>
                <Divider className={styles.divider} />
                <Alert
                    className={styles.alertMargin}
                    type="info"
                    message={alertMessage}
                    showIcon/>
                <Table
                    className={`white-space-nowrap ${styles.tableCursor}`}
                    rowKey="id"
                    dataSource={data.content}
                    columns={columns}
                    onRow={onRow}
                    loading={isFetching}
                    pagination={pagination}
                    onChange={this.handleTableChange}
                    rowSelection={rowSelection}
                    {...TABLE}
                    locale={{
                        emptyText: message ? COMMON_TABLE_QUERY_FAIL_TEXT : COMMON_TABLE_EMPTY_TEXT
                    }}/>
            </Spin>
        );
    }
}

export default DetailSelectPanel;
